package com.stn.zjx.givingtreasure.activity.bi;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.ExportKeystoreDomain;
import com.stn.zjx.givingtreasure.domain.ExportPrivateKeyDomain;
import com.stn.zjx.givingtreasure.domain.GetEthBalanceDomain;
import com.stn.zjx.givingtreasure.event.BiMainRefreshEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.EthNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.service.WalletUserService;
import com.stn.zjx.givingtreasure.table.WalletUser;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.EventBus;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class WalletBackUpActivity extends BaseActivity {
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.skip_bt)
    TextView skipBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.more_bt)
    RelativeLayout moreBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.search_iv)
    ImageView searchIv;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.search_bg)
    RelativeLayout searchBg;
    @BindView(R.id.avatar_civ)
    CircleImageView avatarCiv;
    @BindView(R.id.name_edit)
    EditText nameEdit;
    @BindView(R.id.export_privatekey_bt)
    RelativeLayout exportPrivatekeyBt;
    @BindView(R.id.export_keystore_bt)
    RelativeLayout exportKeystoreBt;
    @BindView(R.id.back_up_bt)
    ButtonBgUi backUpBt;
    @BindView(R.id.delete_bt)
    ButtonBgUi deleteBt;
    @BindView(R.id.save_bt)
    TextView saveBt;
    @BindView(R.id.balance_tv)
    TextView balanceTv;
    @BindView(R.id.address_tv)
    TextView addressTv;
    private String address = "";
    public WalletUser walletUser;


    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        address = getIntent().getStringExtra("address");
        walletUser = WalletUserService.getInstance(this)
                .getWalletUser(address);
        if (walletUser == null) {
            return;
        }
        saveBt.setVisibility(View.VISIBLE);
        nameEdit.setText(walletUser.getName());
        nameEdit.setSelection(nameEdit.getText().length());
        actionTitle.setText(String.valueOf(walletUser.getName()));
        if (TextUtils.isEmpty(walletUser.getMnemonic())) {
            backUpBt.setVisibility(View.GONE);
        } else {
            backUpBt.setVisibility(View.VISIBLE);
        }
        addressTv.setText(address.substring(0, 10) + "..." + address.substring(address.length() - 10, address.length()));
        get_eth_balance(address,"",0);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet_back_up);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt, R.id.export_privatekey_bt, R.id.export_keystore_bt, R.id.back_up_bt, R.id.delete_bt,
            R.id.save_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.export_privatekey_bt:
                initInputPassword(0);
                break;
            case R.id.export_keystore_bt:
                initInputPassword(1);
                break;
            case R.id.back_up_bt:
                initInputPassword(2);
                break;
            case R.id.delete_bt:
                initInputPassword(3);

                break;
            case R.id.save_bt:
                 if(TextUtils.isEmpty(nameEdit.getText().toString().trim())){
                     showToast(getString(R.string.please_input_wallet_name));
                     return;
                 }
                if(!ToolsUtils.checkName(nameEdit.getText().toString().trim())){
                    showToast(getString(R.string.wallet_name_pattern));
                    return;
                }
                 walletUser.setName(nameEdit.getText().toString().trim());
                WalletUserService
                        .getInstance(this)
                        .updateWalletUser(walletUser);
                BiMainRefreshEvent biMainRefreshEvent=new BiMainRefreshEvent();
                 biMainRefreshEvent.flag=BiMainRefreshEvent.RENAME;
                EventBus.getDefault().post(biMainRefreshEvent);
                finish();
                break;
        }
    }
   //获取ETH余额
    public void get_eth_balance(String ethAddress,
                                String ethTokenAddress,
                                Integer ethTokenDecimal
                                ){
        EthNetImpl.get_eth_balance(ethAddress,ethTokenAddress,ethTokenDecimal,"ETH", ethAddress+ethTokenAddress  + "_get_eth_balance",
                new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                           if(response.isSuccessful()&&!isFinishing()){
                               GetEthBalanceDomain domain=new Gson().fromJson(response.body(),GetEthBalanceDomain.class);
                               switch (domain.getStatus()){
                                   case BaseApi.REQUEST_SUCCESS_CODE:
                                       balanceTv.setText(String.valueOf(domain.getData().getBalance())+" Ether");
                                       break;
                                     default:
                                         balanceTv.setText("0 Ether");
                                         break;
                               }
                           }
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if(response.isSuccessful()&&!isFinishing()){
                            GetEthBalanceDomain domain=new Gson().fromJson(response.body(),GetEthBalanceDomain.class);
                            switch (domain.getStatus()){
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    balanceTv.setText(String.valueOf(domain.getData().getBalance())+" Ether");
                                    break;
                                default:
                                    balanceTv.setText("0 Ether");
                                    break;
                            }
                        }
                    }
                });
    }
   //0 导出私钥 1导出keystore 2备份助记词 3删除钱包
    public void initInputPassword(Integer type){
        Dialog dialog=new Dialog(this,R.style.dialog_soft_input);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.dialog_input_wallet_password);
        EditText passwordEdit=dialog.findViewById(R.id.password_edit);
        View cancel_bt=dialog.findViewById(R.id.cancel_bt);
        cancel_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        View sure_bt=dialog.findViewById(R.id.sure_bt);
        sure_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WalletUser db=WalletUserService.getInstance(getApplicationContext())
                        .getWalletUser(address);
                if(db==null){
                    showToast(getString(R.string.db_error));
                    return;
                }

                switch (type){
                    case 0:
                        exportPrivateKey(passwordEdit.getText().toString().trim(),dialog);
                        break;
                    case 1:
                        exportKeystore(passwordEdit.getText().toString().trim(),dialog);
                        break;
                    case 2:
                        backUp(passwordEdit.getText().toString().trim(),dialog);
                        break;
                    case 3:
                        if(!db.getTradepassword().equals(passwordEdit.getText().toString().trim())){
                            dialog.dismiss();
                           showToast(getString(R.string.wallet_password_error));
                            return;
                        }
                        deleteWallet(dialog);
                        break;
                }

            }
        });
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {

                //   SoftInputUtils.openSoftInput(FirstCreateEthBackUpActivity.this, dialog.getCurrentFocus(), 50);

            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                //       SoftInputUtils.closedSoftInput(FirstCreateEthBackUpActivity.this);
//                im.hideSoftInputFromWindow(guest_content_edit.getWindowToken(),0);
                passwordEdit.getText().clear();
            }
        });
        dialog.show();

    }

    public  void backUp(String password,Dialog dialog){
        if(walletUser.getTradepassword().equals(password)){
            Bundle bundle=new Bundle();
            bundle.putString("mnemonic",walletUser.getMnemonic());
            RxActivityTool.skipActivity(getApplicationContext(),BackUpMnemonicActivity.class,bundle);
            dialog.dismiss();
        }else{
            showToast(getString(R.string.wallet_password_error));

        }

    }
    public  void exportPrivateKey(String password,Dialog dialog){
        dialog.dismiss();
        EthNetImpl.export_eth_privatekey(address,password, address + "_export_eth_privatekey",
                new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                       showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                         dissmissLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if(response.isSuccessful()&&!isFinishing()){
                            ExportPrivateKeyDomain domain=new Gson().fromJson(response.body(),ExportPrivateKeyDomain.class);
                            switch (domain.getStatus()){
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    showPrivateKey(domain.getData().getPrivatekey());
                                    break;
                                default:
                                   showToast(domain.getMessage());
                                    break;
                            }
                        }

                    }
                });

    }
    public  void exportKeystore(String password,Dialog dialog){
        dialog.dismiss();
        EthNetImpl.export_eth_keystore(address,password, address + "_export_eth_keystore",
                new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        dissmissLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if(response.isSuccessful()&&!isFinishing()){
                            ExportKeystoreDomain domain=new Gson().fromJson(response.body(),ExportKeystoreDomain.class);
                            switch (domain.getStatus()){
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                 Bundle bundle=new Bundle();
                                 bundle.putString("keystore",domain.getData().getKeystore());
                                    RxActivityTool.skipActivity(WalletBackUpActivity.this,ExportKeyStoreActivity.class,bundle);
                                    break;
                                default:
                                    showToast(domain.getMessage());
                                    break;
                            }
                        }

                    }
                });

    }

    public void showPrivateKey(String content){
         Dialog showPrivate=new Dialog(this);
         showPrivate.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
         showPrivate.setContentView(R.layout.dialog_show_wallet_privatekey);
       TextView contentTv=showPrivate.findViewById(R.id.content);
         ButtonBgUi   copyBt=showPrivate.findViewById(R.id.copy_bt);
         contentTv.setText(content);
         copyBt.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                 if(ToolsUtils.copyKeybroadContent(WalletBackUpActivity.this,content)){
                  showToast(getString(R.string.already_copy_content));
                 }else{
                     showToast(getString(R.string.db_error));
                 }

             }
         });
        showPrivate.show();

    }

    @SuppressLint("CheckResult")
    public void deleteWallet(Dialog dialog){
        dialog.dismiss();
        showLoading();
        Observable.create((ObservableOnSubscribe<String>) emitter -> {
             Thread.sleep(1500);
             emitter.onNext("success");

        }).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {

            }
        }).doOnComplete(new Action() {
            @Override
            public void run() throws Exception {

            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                dissmissLoading();
              boolean  isDelete=WalletUserService.getInstance(WalletBackUpActivity.this)
                        .deleteWalletUser(walletUser);
                 if(isDelete){
                     Set<String> sets=new HashSet<String>();
                     String alias_address=walletUser.getAddress().substring(2,walletUser.getAddress().length());
                     sets.add(alias_address+"");
                     JPushInterface.deleteTags(getApplicationContext(),1,sets);
                     BiMainRefreshEvent biMainRefreshEvent=new BiMainRefreshEvent();
                     biMainRefreshEvent.flag=BiMainRefreshEvent.DELETE;
                     EventBus.getDefault().post(biMainRefreshEvent);
                     finish();
                 }else{
                     showToast(getString(R.string.db_error));
                 }
            }
        });
    }
}
